package com.licheng.aop;


import com.licheng.mapper.OperateLogMapper;
import com.licheng.pojo.OperateLog;
import com.licheng.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Component
//@Aspect
public class OperateLogAop {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    OperateLogMapper operateLogMapper;

    @Pointcut("@annotation(com.licheng.anno.Log)")
    public void pt(){};

    @Around("pt()")
    public Object recordTimeAop(ProceedingJoinPoint pjp) throws Throwable {

        //操作人id
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        Integer operate_emp_id = (Integer) claims.get("id");
        //操作时间
        LocalDateTime operate_time = LocalDateTime.now();
        //执行目标方法的全类名
        String class_name = pjp.getTarget().getClass().getName();
        //执行目标方法名
        String method_name = pjp.getSignature().getName();
        //目标方法运行时参数
        String method_params = Arrays.toString(pjp.getArgs());

        //执行目标方法前时间
        long start = System.currentTimeMillis();
        //目标方法返回值
        Object ret = pjp.proceed();
        //目标方法返时间
        long end = System.currentTimeMillis();
        long cost_time = end - start;

        String return_value = ret.toString();
        if (return_value == null) {
            return_value = "";
        }
        OperateLog oLog = new OperateLog(null, operate_emp_id, operate_time,
                class_name, method_name, method_params, return_value, cost_time, null);
        //调用数据库插入日志信息
        operateLogMapper.insert(oLog);
        return ret;
    }

}
